package com.jijuxie.house.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jijuxie.common.core.R;
import com.jijuxie.house.domain.HouseInfo;
import com.jijuxie.house.domain.vo.HouseAssignVO;
import com.jijuxie.house.service.IHouseAssignService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 房源分配控制器
 * 处理房源分配给经纪人的相关接口
 *
 * @author jijuxie
 */
@RestController
@RequestMapping("/house/assign")
public class HouseAssignController {

    private static final Logger log = LoggerFactory.getLogger(HouseAssignController.class);

    @Autowired
    private IHouseAssignService houseAssignService;

    /**
     * 获取分配列表
     * 支持分页查询
     * 
     * @param params 查询参数（包含pageNum, pageSize, houseId, agentName等）
     * @return 分页结果
     */
    @GetMapping("/list")
    public R<Page<HouseAssignVO>> list(@RequestParam Map<String, Object> params) {
        try {
            Page<HouseAssignVO> page = houseAssignService.getAssignList(params);
            return R.ok(page);
        } catch (Exception e) {
            log.error("获取房源分配列表失败: ", e);
            return R.fail("获取分配列表失败: " + e.getMessage());
        }
    }

    /**
     * 自动分配房源给经纪人
     * 系统根据经纪人工作量、评分等因素自动匹配合适的经纪人
     *
     * @param houseId 房源ID
     */
    @PostMapping("/auto/{houseId}")
    public R<Void> autoAssign(@PathVariable Long houseId) {
        boolean result = houseAssignService.autoAssignHouse(houseId);
        return result ? R.ok() : R.fail("自动分配房源失败");
    }

    /**
     * 手动指定经纪人负责房源
     *
     * @param houseId 房源ID
     * @param agentId 经纪人ID
     * @param params 额外参数（包括备注等）
     */
    @PostMapping("/manual/{houseId}/{agentId}")
    public R<Void> manualAssign(
            @PathVariable Long houseId, 
            @PathVariable Long agentId,
            @RequestBody(required = false) Map<String, Object> params) {
        Long operatorId = StpUtil.getLoginIdAsLong();
        String remark = params != null && params.containsKey("remark") ? params.get("remark").toString() : null;
        boolean result = houseAssignService.manualAssignHouse(houseId, agentId, operatorId, remark);
        return result ? R.ok() : R.fail("手动分配房源失败");
    }

    /**
     * 取消房源分配
     *
     * @param houseId 房源ID
     * @param agentId 经纪人ID
     */
    @DeleteMapping("/{houseId}/{agentId}")
    public R<Void> cancelAssign(@PathVariable Long houseId, @PathVariable Long agentId) {
        boolean result = houseAssignService.cancelAssign(houseId, agentId);
        return result ? R.ok() : R.fail("取消房源分配失败");
    }

    /**
     * 获取房源的分配情况
     *
     * @param houseId 房源ID
     */
    @GetMapping("/house/{houseId}")
    public R<List<HouseAssignVO>> getHouseAssignList(@PathVariable Long houseId) {
        List<HouseAssignVO> list = houseAssignService.getHouseAssignList(houseId);
        return R.ok(list);
    }

    /**
     * 获取经纪人负责的房源列表
     *
     * @param agentId 经纪人ID
     * @param pageNum 页码
     * @param pageSize 每页数量
     */
    @GetMapping("/agent/{agentId}")
    public R<Page<HouseAssignVO>> getAgentHouseList(
            @PathVariable Long agentId,
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<HouseAssignVO> page = new Page<>(pageNum, pageSize);
        Page<HouseAssignVO> result = houseAssignService.getAgentHouseList(page, agentId);
        return R.ok(result);
    }

    /**
     * 获取待分配的房源列表
     */
    @GetMapping("/unassigned")
    public R<List<HouseInfo>> getUnassignedHouses() {
        try {
            log.info("获取待分配房源列表");
            List<HouseInfo> list = houseAssignService.getUnassignedHouses();
            log.info("待分配房源数量: {}", list.size());
            if (list.isEmpty()) {
                log.info("没有找到待分配的房源");
            } else {
                for (HouseInfo house : list) {
                    log.info("待分配房源: ID={}, 标题={}, agent_id={}", house.getHouseId(), house.getTitle(), house.getAgentId());
                }
            }
            return R.ok(list);
        } catch (Exception e) {
            log.error("获取待分配房源列表异常", e);
            return R.fail("获取待分配房源列表失败: " + e.getMessage());
        }
    }
    
    /**
     * 分页获取待分配的房源列表
     */
    @GetMapping("/unassigned/page")
    public R<Page<HouseInfo>> getUnassignedHousesPage(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize) {
        
        try {
            log.info("分页获取待分配房源列表: pageNum={}, pageSize={}", pageNum, pageSize);
            Page<HouseInfo> page = new Page<>(pageNum, pageSize);
            page = houseAssignService.getUnassignedHousesPage(page);
            log.info("待分配房源数量: {}", page.getRecords().size());
            return R.ok(page);
        } catch (Exception e) {
            log.error("分页获取待分配房源列表异常", e);
            return R.fail("获取待分配房源列表失败: " + e.getMessage());
        }
    }
} 